//
//  SinglePage.m
//  Dolphin
//
//  Created by Handymood on 11-5-22.
//  Copyright 2011 __Hanydmood__. All rights reserved.
//

#import "SinglePage.h"
@implementation SinglePage

@synthesize page_id;
@synthesize layers_num;
@synthesize hasMedia;
@synthesize mediaAutoPlay;
@synthesize mediaIndex;
@synthesize resizeMode;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        layers = [[NSMutableSet alloc] init];
        layers_num = 0;
        hasMedia = FALSE;
        mediaAutoPlay = FALSE;
        mediaIndex = -1;
        bringToFrontTimeTick = 0;
        resizeMode = 1;

        originalWidth = 768;
        originalHeight = 1024;
        
        useSpecificScroll = false;
        
        //self scroll setting
        self.delegate = self;
		self.showsHorizontalScrollIndicator = NO;
		self.showsVerticalScrollIndicator = NO;
        self.contentSize = frame.size;
        self.pagingEnabled = TRUE;
        self.minimumZoomScale = 1;
        self.maximumZoomScale = 1;
        self.zoomScale = 1;
        
        //content scroll setting
        contentHolder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [self addSubview:contentHolder];
    }
    return self;
}

-(void) initWithPageInfo:(SinglePageInfo *)singlePageInfo
{
    self.minimumZoomScale = singlePageInfo.single_page_zoom_min;
    self.maximumZoomScale = singlePageInfo.single_page_zoom_max;
    self.zoomScale = 1;

    resizeMode = singlePageInfo.resizeMode;
    
    if (resizeMode != 0) 
    {
        originalWidth = singlePageInfo.ori_page_width;
        originalHeight = singlePageInfo.ori_page_height;
    }

    if (singlePageInfo.scroll_width <= 0 || singlePageInfo.scroll_height <= 0)
    {
        useSpecificScroll = false;
        return;
    }
    else
    {
        useSpecificScroll = true;

        self.contentSize = CGSizeMake(singlePageInfo.scroll_width, singlePageInfo.scroll_height);
    }
}

-(void) scrollViewDidScroll:(UIScrollView *)sender
{
    if(self.contentSize.width<=3072)
    {
        return;
    }
    
        BOOL leftSide = TRUE;

    /*
        if(abs(self.contentOffset.x-self.contentSize.width)<1024+5)
        {
            self.contentOffset = CGPointMake(0, 0);
            
            for (UIComponentBase* page in layers) 
            {
                if (page.orix<1024) 
                {
                    page.frame = CGRectMake(page.orix, page.oriy, 
                    page.frame.size.width, page.frame.size.height);
                }
            }
        }
        else
        {
     */
            if(self.contentOffset.x>self.contentSize.width/2)
            {
                leftSide = FALSE;
            }
            
            for (UIComponentBase* page in layers) 
            {
                if (page.orix<1024) 
                {
                    if (!leftSide) 
                    {
                        page.frame = CGRectMake(page.orix+self.contentSize.width-1024, page.oriy, 
                                                page.frame.size.width, page.frame.size.height);
                    }
                    else
                    {
                        page.frame = CGRectMake(page.orix, page.oriy, 
                                                page.frame.size.width, page.frame.size.height);
                    }
                }
            }
}


-(void) active
{
    if (self.zoomScale != self.minimumZoomScale)
    {
        int stack_width = self.contentSize.width;
        int stack_height = self.contentSize.height;
        self.zoomScale = self.minimumZoomScale;
        self.contentSize = CGSizeMake(stack_width, stack_height);
    }
     
    [self setContentOffset:CGPointMake(0, 0) animated:YES];
    
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
/*
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

//add with image layer
-(void) addImage:(NSString *) imgPath
            imgPos:(CGPoint) inPos
            imgSize:(CGSize)inSize 
            useOriginalSize:(BOOL) inUseOriginalSize
            ratioMode:(int) inRatioMode
            targetId:(int) inTargetId
            layerInfo:(LayerInfo *) singleLayerInfo
{
    if(imgPath == Nil || [imgPath length] <=4)
    {
        return;
    }
    
    UIImageLayer*uiImageView =[[UIImageLayer alloc] initWithFrame:CGRectMake(inPos.x,inPos.y, inSize.width,inSize.height)];
    [uiImageView initImage:imgPath useOriginalSize:inUseOriginalSize ratioMode:inRatioMode layerInfo:singleLayerInfo]; 
  
    if (singleLayerInfo.msg) 
    {
        [uiImageView initHitMsg:singleLayerInfo.msg];
        
        if ([singleLayerInfo.msg isEqualToString:@"trigger_video"] && singleLayerInfo.target_video_path != Nil) 
        {
            uiImageView.target_album_xml = [[NSString alloc] initWithString:singleLayerInfo.target_video_path];
        }
    }
    else if (singleLayerInfo.target_album_xml) 
    {
        [uiImageView initHitMsg:@"album_trigger"];
    }
    else if(inTargetId != -1) 
    {
        uiImageView.button_id = inTargetId;
        [uiImageView initHitMsg:@"page_id_trigger"];
    }
    else
    {
        [uiImageView initHitMsg:@"img_single_tap"];
    }
    
    [layers addObject:uiImageView];
    [contentHolder addSubview:uiImageView];
    
    uiImageView.orix = inPos.x;
    uiImageView.oriy = inPos.y;
    
    /*
    if (singleLayerInfo.ani == 1) 
    {
        uiImageView.orix = inPos.x-singleLayerInfo.startOffX;
        uiImageView.oriy = inPos.y-singleLayerInfo.startOffY;
    }
     */
    
    if (singleLayerInfo.transitionType > 0) 
    {
        //UIViewAnimationCurveEaseIn
        
        UIViewAnimationCurve curve;
        
        if (singleLayerInfo.transitionType == 1) 
        {
            curve = UIViewAnimationCurveLinear;
        }
        else  if (singleLayerInfo.transitionType == 2) 
        {
            curve = UIViewAnimationCurveEaseIn;
        }
        else  if (singleLayerInfo.transitionType == 3) 
        {
            curve = UIViewAnimationCurveEaseOut;
        }
        else  if (singleLayerInfo.transitionType == 4) 
        {
            curve = UIViewAnimationCurveEaseInOut;
        }  
        
        uiImageView.transform = CGAffineTransformMakeTranslation(singleLayerInfo.startOffX,
                                                                                                           singleLayerInfo.startOffY );
        uiImageView.alpha = singleLayerInfo.startAlpha;
        
        [UIView animateWithDuration:singleLayerInfo.duration
                              delay:singleLayerInfo.delay
                            options:curve 
                         animations:^
                        {
                             uiImageView.transform = CGAffineTransformMakeTranslation(0,0);
                             uiImageView.alpha = 1.0f;
                            

                         }
                         completion:NULL];
    }
}

-(void)addVideoPlayer:(NSString *)inVideoPath
             videoPos:(CGPoint) inPos
            videoSize:(CGSize )inSize
             autoPlay:(BOOL) inAutoPlay 
               isLoop:(BOOL) inLoop
            layerInfo:(LayerInfo *) singleLayerInfo
slideshowAutoPlay:(BOOL) isSlideshowAutoPlay
           slideBgmOn:(BOOL) isSlideBgmOn
                       fade:(BOOL) isFade;
{
    if(inVideoPath == Nil || [inVideoPath length] <=4)
    {
        return;
    }
    
    SimpleVideoPlayer *simpleVideoPlayer = [[SimpleVideoPlayer alloc] init];

    [simpleVideoPlayer initVideoPlayer:inVideoPath  
                                    videoSize:inSize 
                                    autoPlay:inAutoPlay 
                                    isLoop:inLoop 
                                    ratioMode:singleLayerInfo.ratioMode
                                    playerStyle:singleLayerInfo.style 
                                    slideshowAutoPlay:isSlideshowAutoPlay
                                    slideBgmOn:isSlideBgmOn
                                    inFade:isFade];
    
    [simpleVideoPlayer setXY:inPos.x offy:inPos.y];
    
    simpleVideoPlayer.orix = inPos.x;
    simpleVideoPlayer.oriy = inPos.y;
    
    [layers addObject:simpleVideoPlayer];
    [contentHolder addSubview:simpleVideoPlayer];
    
    if(inPos.y + inSize.height > contentHolder.frame.size.height)
    {
        contentHolder.frame = CGRectMake(contentHolder.frame.origin.x, contentHolder.frame.origin.y, 
                                         contentHolder.frame.size.width, inPos.y + inSize.height);
    }
}

-(void)addBtnSlide:(NSArray *)imgArray 
          slidePos:(CGPoint) inPos
         slideSize:(CGSize ) inSlideSize 
           imgSize:(CGSize ) inImgSize
          layerInfo:(LayerInfo *) singleLayerInfo
{
    ButtonSlide *buttonSlide = [[ButtonSlide alloc] init];
    
    [buttonSlide initWithImages:imgArray slideSize:inSlideSize imgSize:inImgSize];
    [buttonSlide setXY:inPos.x offy:inPos.y];
    
    [layers addObject:buttonSlide];
    [contentHolder addSubview:buttonSlide]; 
}

-(void)addAudio:(NSString *)audioPath
           audioPos:(CGPoint) inPos
            autoPlay:(BOOL) inAutoPlay 
              isLoop:(BOOL) inLoop
   isButtonShow:(BOOL) inButtonShow
           layerInfo:(LayerInfo *) singleLayerInfo
{
    SimpleAudioPlayer *audioPlayer = [[SimpleAudioPlayer alloc] init];
    [audioPlayer initAudioPlayer:audioPath autoPlay:inAutoPlay isLoop:inLoop isButtonShow:inButtonShow];
    [audioPlayer setXY:inPos.x offy:inPos.y];
    
    [layers addObject:audioPlayer];
    [contentHolder addSubview:audioPlayer]; 
}

-(void) layoutAdjustWithOrientation:(UIInterfaceOrientation)interfaceOrientation
                   isLandScapeTwoPage:(BOOL) inLandScapeTwoPage
                                                isInit:(BOOL) inIsInit;
{
    if (resizeMode == 0) //bottom layer auto resizing
    {
        CGFloat stack_width = self.contentSize.width;
        CGFloat stack_height = self.contentSize.height;
        self.zoomScale = 1;
        self.contentSize = CGSizeMake(stack_width, stack_height);

        contentHolder.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        if (inLandScapeTwoPage && !inIsInit) 
        {
            CGFloat originalRatio = originalWidth/originalHeight;
            CGFloat curRatio = self.frame.size.width/self.frame.size.height;
            
            CGFloat targetWidth;
            CGFloat targetHeight;
            
            if (originalRatio<curRatio)//limit by frame height 
            {
                targetWidth = self.frame.size.height*originalRatio;
                targetHeight = self.frame.size.height;
            }
            else //limit by frame width
            {
                targetWidth = self.frame.size.width;
                targetHeight = self.frame.size.width/originalRatio; 
            }

            contentHolder.frame = CGRectMake((self.frame.size.width-targetWidth)/2, (self.frame.size.height-targetHeight)/2, 
                                             self.frame.size.width, self.frame.size.height);
            
            CGFloat targetZoomScale = targetWidth/originalWidth;
            
            self.minimumZoomScale = targetZoomScale;
            self.zoomScale = self.minimumZoomScale;
        }
        else if(inLandScapeTwoPage && inIsInit)
        {
            contentHolder.frame = CGRectMake(-self.frame.size.width/2, contentHolder.frame.origin.y, 
                                                                         contentHolder.frame.size.width, contentHolder.frame.size.height);
        }

        if (useSpecificScroll) 
        {
            CGFloat ratio = originalWidth/self.frame.size.width;
            
            if(originalHeight/self.frame.size.height < ratio)
            {
                ratio = originalHeight/self.frame.size.height;
            }

            self.contentSize = CGSizeMake(stack_width*ratio, stack_height*ratio);
        }
        else
        {
            self.contentSize = contentHolder.frame.size;
        }
            
    }
    else if(resizeMode == 1) //page auto resizing
    {
        CGFloat curPageWidth = originalWidth;
        CGFloat curPageHeight = originalHeight;
        
        CGFloat curFrameWidth = self.frame.size.width;
        CGFloat curFrameHeight = self.frame.size.height;
        
        CGFloat originalRatio = curPageWidth/curPageHeight;
        CGFloat curRatio = curFrameWidth/curFrameHeight;
        
        CGFloat targetWidth;
        CGFloat targetHeight;

        if (originalRatio<curRatio)//limit by frame height 
        {
            targetWidth = curFrameHeight*originalRatio;
            targetHeight = curFrameHeight;
        }
        else //limit by frame width
        {
            targetWidth = curFrameWidth;
            targetHeight = curFrameWidth/originalRatio; 
        }
    
        CGFloat targetZoomScale = targetWidth/originalWidth;
        
        contentHolder.frame = CGRectMake((self.frame.size.width-targetWidth)/2, (self.frame.size.height-targetHeight)/2, 
                                                                     curPageWidth, curPageHeight);
        
        self.minimumZoomScale = targetZoomScale;
        int stack_width = self.contentSize.width;
        int stack_height = self.contentSize.height;
        self.zoomScale = self.minimumZoomScale;
        self.contentSize = CGSizeMake(stack_width, stack_height);
        
        if (useSpecificScroll) 
        {
            CGFloat ratio = originalWidth/self.frame.size.width;
            
            if(originalHeight/self.frame.size.height < ratio)
            {
                ratio = originalHeight/self.frame.size.height;
            }
            
            self.contentSize = CGSizeMake(stack_width*ratio, stack_height*ratio);
        }
        else
        {
            self.contentSize = self.frame.size;
        }
    }
}

-(int) curLayersNum
{
    return [[contentHolder subviews] count];
}

-(UIComponentBase *) getLayerAtIndex:(int) index
{
    if (index>=0 && index < [[contentHolder subviews] count]) 
    {
        return [[contentHolder subviews] objectAtIndex:index];
    }
    else
    {
        return Nil;
    }
}


-(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if(bringToFrontTimeTick<2)
    {
        bringToFrontTimeTick++;
    }
    else
    {
        bringToFrontTimeTick = 0;
        [[self superview] bringSubviewToFront:self];
    }
    return contentHolder;
}


-(void) pause
{
    
}
-(void) reset
{
    self.userInteractionEnabled = false;
    
    for (UIComponentBase* page in layers) 
    {
        [page reset];
        [page removeFromSuperview];
        [page release];
    }
    
    [layers removeAllObjects];
    [layers release];

    [contentHolder removeFromSuperview];
    [contentHolder release];
    
    for (UIView*singleView in[self subviews]) 
    {
        [singleView removeFromSuperview];
    }
}

- (void)dealloc
{
    [super dealloc];
}

@end
